from fastapi import APIRouter, File, UploadFile
import os
from pathlib import Path

router = APIRouter()

@router.post("/upload")
def upload(file: bytes = File(...)): # 上传文件，上传的是字节流
    print(len(file))
    return {"file_size": len(file)}

@router.post("/upload_files")
def upload_files(files: list[bytes] = File(...)): # 上传文件，上传的是文件列表
    for file in files:
        print(file)
    return {"files": files}

# 以下是常用方法
@router.post("/upload_file",summary=["文件上传,并保存到服务器"])
def upload_file(file: UploadFile): # 上传文件，上传的是文件对象
    # 使用 pathlib 处理路径
    upload_dir = Path("imgs")
    upload_dir.mkdir(exist_ok=True)
    
    file_path = upload_dir / file.filename
    try:
        content = file.file.read()
        file_path.write_bytes(content)
    except Exception as e:
        return {"error": f"文件保存失败: {str(e)}"}
    finally:
        file.file.close()

    return {
        "filename": file.filename,
        "content_type": file.content_type,
        "size": file.size
    }

@router.post("/upload_files_use_uploadfile",summary=["上传多个文件，并保存到服务器"])
def upload_files_use_uploadfile(files: list[UploadFile]): # 上传文件，上传的是文件列表

    print(files)

    for file in files:  
        # 使用 pathlib 处理路径
        upload_dir = Path("imgs")
        upload_dir.mkdir(exist_ok=True)

        file_path = upload_dir / file.filename
        try:
            content = file.file.read()
            file_path.write_bytes(content)
        except Exception as e:
            return {"error": f"文件保存失败: {str(e)}"}

    return {"message": "文件上传成功", "files": [file.filename for file in files]}
